package edu.johnpank.libassistant.services

import edu.johnpank.libassistant.entity.BorrowedBook
import edu.johnpank.libassistant.repo.BorrowedBookRepository
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
import java.util.Optional

@Service
class BorrowedBookService(
    @Autowired
    private val borrowedBookRepository: BorrowedBookRepository
) {

    fun getAllBorrowedBookHistory():MutableList<BorrowedBook>{
        return borrowedBookRepository.findAll()
    }

    @Transactional
    fun addBorrowedBook(borrowedBook: BorrowedBook){
        borrowedBookRepository.save(borrowedBook)
    }

    fun getAllNotReturnedBookByReader(readerId: Long): MutableList<BorrowedBook>{
        return borrowedBookRepository.findAllByReaderIdAndReturned(readerId, false)
    }

    fun checkBookIsNotReturned(bookId: Long): Boolean{
        if (borrowedBookRepository.findAllByBookIdAndReturned(bookId, false).isNotEmpty())
            return true
        return false
    }

    fun getBorrowedBookForReturn(readerId: Long, bookId: Long): Optional<BorrowedBook>{
        return borrowedBookRepository.findByReaderIdAndBookIdAndReturned(readerId, bookId,false)
    }

    fun updateBorrowedBook(borrowedBook: BorrowedBook){
        borrowedBookRepository.save(borrowedBook)
    }
}